# -*- coding: utf-8 -*-
# @Time      : 2024/5/9 8:40
# @Author    : 未命名
# @File      : test1.py
# @Software  : PyCharm

from bs4 import BeautifulSoup
import re
import urllib.request,urllib.error
import xlwt
import sqlite3

def main():
    #测试urllib模块是否返回html元素
    # askUrl("http://movie.douban.com/top250")
    #
    baseurl = "http://movie.douban.com/top250?start="   #此时start后加的参数在下面获取的url中有所改变
    # getDate(baseurl)
    # print(getDate(baseurl))
    datalist = getDate(baseurl)
    # savepath =".\\豆瓣电影Top250.xls"
    # saveDate(datalist,savepath)

    dbpath = "movie.db"
    saveData2DB(datalist, dbpath)




#正则表达式进行校验,影评链接的规则
findLink = re.compile(r'<a href="(.*?)">')
#影片照片的规则
findImgSrc = re.compile(r'<img.*src="(.*?)"')
#影片标题的规则
findTitle = re.compile(r'<span class="title">(.*?)</span>')
#影片评分的规则
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')
#评价人数规则
findJudge = re.compile(r'<span>(\d*)人评价</span>')
#概况规则
findInq = re.compile(r'<span class="inq">(.*)</span>')
#相关内容规则
findBd = re.compile(r'<p class="">(.*?)</p>',re.S)  #re.忽略换行
def getDate(baseurl):
    datalist = []  #创建列表，方便后期保存的爬取数据。
    for i in range(0,10):   #循环十次（调用十次），调用获取页面信息的函数。
        url = baseurl + str((i*25))  #python中int不能直接加到str后，强转,拼接url,方便调用askurl函数，获取每页的html元素
        html = askUrl(url)
        #解析数据
        soup = BeautifulSoup(html,'html.parser')  #对整体进行解析
        for item in soup.find_all("div",class_= "item"):
            #print(item)
            data = []
            item = str(item)  #强制转换为字符串格式，方便后期正则效正
            link = re.findall(findLink,item)[0]
            #print(link)
            data.append(link)

            imgSrc = re.findall(findImgSrc,item)[0]  #re库的正则表达式，先将item转换为字符串格式，再进行正则匹配
            data.append(imgSrc)


            titles = re.findall(findTitle,item)   #片名可能只有一个中文名，外文名可能没有，进行分别设置
            if (len(titles) == 2):
                ctitle = titles[0]    #表示列表中的第一个参数，也就是中文名称
                data.append(ctitle)
                otitle = titles[1].replace("/","") #将外文名的特殊字符替换掉
                data.append(otitle)
            else:
                data.append(titles[0])
                data.append(' ')

            rating = re.findall(findRating,item)[0]
            data.append(rating)

            judeNum = re.findall(findJudge,item)[0]
            data.append(judeNum)

            inq = re.findall(findInq,item)
            if len(inq) != 0:
                inq = inq[0].replace("。","")   #去句号
                data.append(inq)             #添加概述
            else:
                data.append(' ')   #如果概述没内容，进行添加

            bd = re.findall(findBd,item)[0]
            bd = re.sub(r'<br(\s+)?/>',"",bd)  #去掉</br>
            bd = re.sub('/',' ',bd)  #去掉/
            data.append(bd.strip())   #strip()  去掉空格的方法

            datalist.append(data)   #把处理的一条数据添加到datalist中
    return datalist


def saveDate(datalist,path):
    book =xlwt.Workbook(encoding="utf-8", style_compression=0)  #对数据进行压缩
    sheet = book.add_sheet("豆瓣电影Top250",cell_overwrite_ok=True)  #覆盖之前的内容
    col = ("电影详情链接","图片链接","影片中文名","影片外文名","评分","评价人数","概述","相关信息")
    for i in range (0,8):
          sheet.write(0,i,col[i])
    for i in range(0,250):
        # print("第%d条"%(i+1))
        data = datalist[i]
        for j in range(0,8):
            sheet.write(i+1,j,data[j])
    book.save(path)



def saveData2DB(datalist,dbpath):
    init_db(dbpath)
    conn = sqlite3.connect(dbpath)
    cur = conn.cursor()

    for data in datalist:
        for index in range(len(data)):
            if index == 4 or index == 5:
                continue
            data[index] = '"'+str(data[index])+'"'
        sql = '''
              insert into movie250(info_link,pic_link,cname,oname,score,rated,instroduction,info)
              values (%s)
        '''%",".join(data)
        #print(sql)
        cur.execute(sql)
        conn.commit()
    cur.close()
    conn.close()


def init_db(dbpath):
    sql = '''
        CREATE TABLE movie250
        (
             id integer PRIMARY KEY autoincrement ,
             info_link text ,
             pic_link text ,
             cname varchar ,
             oname varchar , 
             score numeric ,
             rated numeric ,
             instroduction text ,
             info text
        );
    '''
    conn = sqlite3.connect(dbpath)
    cursor = conn.cursor()
    cursor.execute(sql)
    conn.commit()
    conn.close()


def askUrl(url):
    head = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.54"
    }
    request = urllib.request.Request(url,headers=head)
    try:
        response = urllib.request.urlopen(request)
        html = response.read().decode("utf-8")
        # print(html)  #暂时不用进行打印
    except urllib.error.URLError as e:
        if hasattr(e,'code'):
            print(e.code)
        if hasattr(e,'reason'):
            print(e.reason)
    return html



if __name__ == "__main__":
    main()
